package com.zzy.controller;

import com.zzy.Pojo.*;
import com.zzy.service.serviceimpl.ShoppingServiceImpl;
import com.zzy.utils.OrderId;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/mall")
public class MyMallRest
{
    @Resource
    MyRest myRest;
    @Resource
    ShoppingServiceImpl shoppingService;
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    //查询账户及其余额
    @RequestMapping("/czzh")
    public MyRest czzh(@RequestBody Map<String,String> map )
    {
        String accountID = map.get("accountID");
        Account account = shoppingService.getAccount(accountID);
        //生成一个随机字符串
        String orderIdByTime = OrderId.getOrderIdByTime();
        redisTemplate.opsForValue().set("zzy"+orderIdByTime,1);//存到reids
        if(account==null)
        {
            myRest.setCode(100);
            myRest.setMsg("no");
            return myRest;
        }
        else
        {
            Map<String,Object> m = new HashMap<>();
            m.put("account",account);
            m.put("orderId",orderIdByTime);
            myRest.setCode(200);
            myRest.setMsg("ok");
            myRest.setData(m);
            return myRest;
        }

    }
    //支付宝充值提交订单
    @RequestMapping("/paycz.do")
    public MyRest paycz(@RequestBody Order order)
    {
        //判断是不是第一次进接口
        if(redisTemplate.hasKey("zzy"+order.getOrderId()))
        {
            //是第一次，删除掉这个key,执行操作
            //创建一个充值记录
            Chongzhi chongzhi = new Chongzhi();
            chongzhi.setRecordId("zzy"+order.getOrderId());//记录ID
            chongzhi.setAccountID(order.getOrderTitle());//充值账户
            chongzhi.setPeople("370111");//充值人id
            chongzhi.setUpmoney(order.getOrderMoney());//本次充值金额
            chongzhi.setStatus("1");
            int i = shoppingService.addAccount(chongzhi);

            OrderMsg orderMsg = new OrderMsg();
            orderMsg.setOut_trade_no("zzy"+order.getOrderId());
            orderMsg.setSubject(order.getOrderId());
            orderMsg.setNotify_url("http://538s69k093.qicp.vip:11058/mall/payresult.do");
            orderMsg.setReturn_url("http://538s69k093.qicp.vip:11058/zfcg.html");
            BigDecimal orderMoney = order.getOrderMoney();
            String money = String.valueOf(orderMoney);
            orderMsg.setTotal_amount(money);
            //调用支付宝支付接口
            String url="http://127.0.0.1:8189/wangguan/zhifu";
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<MyRest> entity = restTemplate.postForEntity(url,orderMsg,MyRest.class);
            MyRest body = entity.getBody();
            Object data = body.getData();
            myRest.setMsg("ok");
            myRest.setData( body.getData());
            myRest.setCode(200);
            redisTemplate.delete("zzy"+order.getOrderId());
            return myRest;
        }
        else
        {
            myRest.setMsg("no");
            myRest.setCode(201);
            return myRest;
        }
    }
    //充值回调接口
    @RequestMapping("/payresult.do")
    public void payresult(@RequestBody Map<String,String> map)
    {
        //判断订单状态是否为已支付
        String out_trade_no = map.get("out_trade_no");
        String status = shoppingService.getStatus(out_trade_no);
        if(status.equals("1"))
        {
           //修改账户余额 ,订单状态
            Account accountId = shoppingService.getAccountId(out_trade_no);
            String getmoney = shoppingService.getmoney(out_trade_no);
            int i = shoppingService.updateAccount(accountId,getmoney);
            Chongzhi chongzhi = new Chongzhi();
            chongzhi.setRecordId(out_trade_no);
            chongzhi.setStatus("2");
            int i1 = shoppingService.updateChongzhi(chongzhi);
            System.out.println(i1);
        }
    }
    //前端回调查询订单状态
    @RequestMapping("orderStatus.do")
    public MyRest orderStatus(@RequestBody Order  o)
    {
        String orderId = o.getOrderId();
        orderId =orderId.replace("+"," ");
        String s = shoppingService.getStatus(orderId);
        if(s.equals("2"))
        {
            myRest.setCode(200);
            myRest.setMsg("订单支付成功");
        }
        else
        {
            myRest.setCode(201);
            myRest.setMsg("订单支付失败");
        }
        return myRest;
    }
    //查询所有账户
    @RequestMapping("/zh")
    public  MyRest getzh()
    {
        List<String> getzh = shoppingService.getzh();
        if(getzh!=null)
        {
            myRest.setData(getzh);
            myRest.setCode(200);
            myRest.setMsg("ok");
            return myRest;
        }
        myRest.setCode(100);
        myRest.setMsg("no");
        return myRest;
    }
    //接收token,并验证,通过即添加自己的cookie
    @GetMapping("/login")
    public void  login(@RequestParam("code") String token,
                       HttpServletResponse resp) throws IOException {
        String url ="http://127.0.0.1:8080/sso/yzToken";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<MyRest> myRest = restTemplate.postForEntity(url, token, MyRest.class);
        MyRest body = myRest.getBody();
        if(body.getCode()==200)
        {
            //验证通过新建个cookie,然后跳转自己的首页
            Cookie cookie = new Cookie("cz",(String)body.getData());
            cookie.setMaxAge(24*60*60*3);
            cookie.setPath("/");
            resp.addCookie(cookie);
            resp.sendRedirect("http://127.0.0.1:8888/");
        }
        else{
           //验证不通过,继续302
            String url1 = "http://127.0.0.1:8080/sso/remember?fanhui=http://127.0.0.1:8888/mall/login";
            url1= URLEncoder.encode(url1);
            resp.sendRedirect(url1);
        }
    }
}
